<template>
  <el-card
    shadow="never"
    :body-style="{ padding: '24px 32px', height: '100%' }"
    class="cus-card">
    <el-form
      ref="form"
      :model="form"
      size="small"
      label-width="80px">
      <el-form-item label="模板名称: ">
        <el-input v-model="form.name" style="width: 200px;"></el-input>
      </el-form-item>
      <el-form-item label="计费方式: ">
        <el-radio-group
          :disabled="this.id !== null"
          v-model="form.valuationType"
          @change="onRadioChange">
          <el-radio :label="1">按件数</el-radio>
          <el-radio :label="2">按重量</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="配送区域: ">
        <el-table
          :data="valuationRules"
          class="express-area"
          style="width: 100%">
          <el-table-column
            prop="region"
            label="可配送区域">
            <template slot-scope="scope">
              <div class="delivery-table__region">
                <div class="delivery-table__region-area">
                  {{ scope.row.regionNames | tableRegionNames }}
                </div>
                <div class="delivery-table__region-actions">
                  <a>修改</a>
                  <a>删除</a>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="firstFee"
            :label="columnLabel[0]"
            width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.firstFee"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            prop="firstAmount"
            :label="columnLabel[1]"
            width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.firstAmount"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            prop="additionalFee"
            :label="columnLabel[2]"
            width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.additionalFee"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            prop="additionalAmount"
            :label="columnLabel[3]"
            width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.additionalAmount"></el-input>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          style="margin-top: 10px;"
          @click="$refs.regionDialog.show()">
          指定可配送区域和运费
        </el-button>
      </el-form-item>
      <el-form-item style="padding-top: 10px;">
        <el-button type="primary" @click="onSubmit">保存</el-button>
        <el-button @click="$router.push({ name: 'express' })">返回</el-button>
      </el-form-item>
    </el-form>

    <region-dialog ref="regionDialog" @change="onRegionDialogChange"></region-dialog>
  </el-card>
</template>

<script>
import { getAreaTree } from '@/api/public'
import {
  createExpressTemplate,
  updateExpressTemplate,
  getExpressDetails
} from '@/api/express';

import RegionDialog from './RegionDialog.vue'

export default {
  components: {
    RegionDialog
  },
  data() {
    return {
      id: null,
      form: {
        name: null,
        valuationType: 1,
        valuationRules: []
      },
      list: [],
      tableDataOption: {
        valuationType_1: {
          columnLabel: ['首件(个)', '运费(元)', '续件(个)', '续费(元)'],
          valuationRules: [],
          valuationRuleTemplate: {
            regionNames: null,
            regions: [],
            firstFee: 1,
            additionalFee: 0.00,
            firstAmount: 0,
            additionalAmount: 0.00
          },
        },
        valuationType_2: {
          columnLabel: ['首重(Kg)', '运费(元)', '续重(Kg)', '续费(元)'],
          valuationRules: [],
          valuationRuleTemplate: {
            regionNames: null,
            regions: [],
            firstFee: 0.1,
            additionalFee: 0.00,
            firstAmount: 0.0,
            additionalAmount: 0.00
          }
        }
      }
    }
  },
  created() {
    if (this.$route.params.id) {
      this.id = this.$route.params.id
    }
    // this.getAreaTree()
    // this.list.push(Object.assign({}, this.dataTemplate[0]))
    this.getExpressDetails()
  },
  computed: {
    columnLabel() {
      return this.tableDataOption[`valuationType_${this.form.valuationType}`].columnLabel
    },
    valuationRules() {
      return this.tableDataOption[`valuationType_${this.form.valuationType}`].valuationRules
    },
    valuationRuleTemplate() {
      return this.tableDataOption[`valuationType_${this.form.valuationType}`].valuationRuleTemplate
    }
  },
  filters: {
    tableRegionNames(val) {
      return Array.isArray(val) ? val.join(',') : val
    }
  },
  methods: {
    getAreaTree() {
      getAreaTree().then(res => {
        console.log(res)
      })
    },
    onRadioChange(val) {
      console.log(val)
    },
    onRegionDialogChange(val) {
      let names = []
      let codes = []
      let getCheckedRegionName = (regions, deep = false) => {
        regions.forEach(region => {
          names.push(region.name)
          codes.push(region.code)
          if (deep && region.children && region.children.length > 0) {
            getCheckedRegionName(region.children, deep)
          }
        })
      }
      for (const key in val) {
        getCheckedRegionName(val[key].regions, false)
      }
      this.valuationRules.push(
        Object.assign(
          {},
          this.valuationRuleTemplate,
          { regionNames: names.join(','), regions: codes }
        ))
    },
    // 获取运费模版详情
    getExpressDetails() {
      getExpressDetails(this.id).then(res => {
        if (res.status === 'success') {
          const { name, valuation_type, valuation_rules } = res.data
          this.form.name = name
          this.form.valuationType = valuation_type
          this.tableDataOption[`valuationType_${this.form.valuationType}`].valuationRules = valuation_rules
        }
      })
    },
    // 新建运费模版
    createExpressTemplate() {
      createExpressTemplate(this.form).then(res => {
        if (res.status === 'success') {
          this.$message({
            type: 'success',
            message: res.message
          })
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      })
    },
    // 更新运费模版
    updateExpressTemplate() {
      updateExpressTemplate(this.id, this.form).then(res => {
        if (res.status === 'success') {
          this.$message({
            type: 'success',
            message: res.message
          })
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      })
    },
    onSubmit() {
      let valuationRules = [];
      this.valuationRules.forEach(rule => {
        valuationRules.push({
          'regions': rule.regions,
          'firstFee': parseInt(rule.firstFee),
          'firstAmount': parseFloat(rule.firstAmount),
          'additionalFee': parseInt(rule.additionalFee),
          'additionalAmount': parseFloat(rule.additionalAmount)
        })
      });
      this.form.valuationRules = valuationRules
      if (this.id) {
        this.updateExpressTemplate()
      } else {
        this.createExpressTemplate()
      }
    }
  }
}
</script>

<style lang="scss">
.express-area {
  &.el-table th.is-leaf {
    background-color: #f7f8fa;
  }
}
.delivery-table__region {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .delivery-table__region-area {
    flex-grow: 1;
  }
  .delivery-table__region-actions {
    display: block;
    padding-left: 20px;
    flex-shrink: 0;
    text-align: right;
    a + a {
      margin-left: 5px;
    }
  }
}
</style>
